#include "mainWindow.h"

using namespace lv::sdk;
using namespace easyWebServer;
using namespace dxy::threadPool;

mainWindow::mainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui_mainWindow)
{


    this->setWindowTitle(tr("D3GUITool"));
    ui->setupUi(this);

    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, [this] () {
        slt(Json)["ImgSizeScalar"] = Json(this->ui->Depth->height() * 0.8 / 480.0);
    });
    // m_timer->start(100);

    m_task = new Task(this, ui->Depth_widget, ui->IR_widget, ui->cloudPoint_widget);
    
    
    configInit();

    slt(LvApi).init();
    slt(DxyThreadPool).start(8);
    slt(Json)["Control"]["IsSetFrameRate"] = Json(false);


    setWindowFlags(Qt::FramelessWindowHint);    //隐藏标题栏（无边框）
    setAttribute(Qt::WA_StyledBackground);      //启用样式背景绘制
    setAttribute(Qt::WA_TranslucentBackground); //背景透明
    setAttribute(Qt::WA_Hover);

    m_model = new QStandardItemModel(this);
    ui->treeView->setModel(m_model);

    connect(ui->minMax, SIGNAL(clicked()), this, SLOT(changeMinMax()));
    connect(ui->leftRightBtn, &QPushButton::clicked, [=] () {
        if(ui->leftRightBtn->isChecked() == true) ui->deviceList_2->hide();
        else ui->deviceList_2->show();
    });
    connect(ui->leftRightBtn_2, &QPushButton::clicked, [=] () {
        if(ui->leftRightBtn_2->isChecked() == true) ui->setZone_2->hide();
        else ui->setZone_2->show();
    });
    connect(ui->findDevices, &QPushButton::clicked, this, &mainWindow::scanDevice);
    connect(ui->treeView, &QAbstractItemView::doubleClicked, this, &mainWindow::on_treeView_clicked);
    connect(ui->openDev, &QPushButton::pressed, this, &mainWindow::on_openClicked);
    connect(ui->closeDev, &QPushButton::pressed, this, &mainWindow::on_stopClicked);

    connect(ui->IRCkBox, &QCheckBox::clicked, [this] (bool checked) {this->m_task->showWindow(ui->IR, checked);});
    connect(ui->DepthCkBox, &QCheckBox::clicked, [this] (bool checked) {this->m_task->showWindow(ui->Depth, checked);});
    connect(ui->CloudPointCkBox, &QCheckBox::clicked, [this] (bool checked) {this->m_task->showWindow(ui->cloudPoint, checked); this->m_task->showWindow(ui->Depth, true);});
    connect(ui->Depth_close, &QPushButton::clicked, [this] () {
        this->ui->Depth->hide();
        ui->CloudPointCkBox->setChecked(false ? ui->CloudPointCkBox->isChecked() : false);
        ui->Black_BG->setEnabled(false);
        this->ui->CloudPointCkBox->setChecked(false);
        this->m_task->showWindow(ui->cloudPoint, false ? ui->CloudPointCkBox->isChecked() : false);
        slt(Json)["Image"]["CloudPoint"] = Json(false);
        slt(Json)["Image"]["CloudPoint"] = Json(false ? ui->CloudPointCkBox->isChecked() : false);
        slt(Json)["Image"]["Depth"] = Json(false);
        ui->DepthCkBox->setChecked(false);
    });
    connect(ui->IR_close, &QPushButton::clicked, [this] () {
        this->ui->IR->hide();
        ui->IRCkBox->setChecked(false);
        slt(Json)["Image"]["IR"] = Json(false);
    });
    connect(ui->CloudPoint_close, &QPushButton::clicked, [this] () {
        this->ui->cloudPoint->hide();
        this->ui->DepthCkBox->setChecked(true);
        this->ui->CloudPointCkBox->setChecked(false);
        slt(Json)["Image"]["Depth"] = Json(true);
        slt(Json)["Image"]["CloudPoint"] = Json(false);
    });
    
    connect(ui->resetCamera, &QPushButton::clicked, [this] () {
        this->m_task->getCloudPointShow()->ResetCamera();
    });

    connect(ui->leftView, &QPushButton::clicked, [this] () {
        this->m_task->getCloudPointShow()->ChangeView(Show3D::ViewPos::Left);
    });
    
    connect(ui->forwardView, &QPushButton::clicked, [this] () {
        this->m_task->getCloudPointShow()->ChangeView(Show3D::ViewPos::Forward);
    });

    connect(ui->downView, &QPushButton::clicked, [this] () {
        this->m_task->getCloudPointShow()->ChangeView(Show3D::ViewPos::Down);
    });

    // connect(ui->Depth, &QWidget::mouseDoubleClickEvent, [] (QMouseEvent * event) {
    //     qDebug() << "clicked";
    // });

    // ui->Depth->layout()->setAlignment(Qt::AlignLeft);

    CONNECTMINMAX(Depth_minMax, Depth, 0, 0)
    CONNECTMINMAX(IR_minMax, IR, 0, 1)
    CONNECTMINMAX(cloudPoint_minMax, cloudPoint, 1, 0)
    m_task->setCallBackForShow3D([this] () {
        if(!this->ui->cloudPoint->isFullScreen())
        {
            ui->cloudPoint->setParent(nullptr);
            ui->cloudPoint->setWindowFlag(Qt::Window);
            ui->cloudPoint->showFullScreen();
            m_task->setFullScreen(true);
        }
        else
        {
            ui->cloudPoint->setParent(ui->widget_6);
            ui->gridLayout_2->addWidget(ui->cloudPoint, 1, 0);
            ui->cloudPoint->setWindowFlag(Qt::SubWindow);
            ui->cloudPoint->showNormal();
            m_task->setFullScreen(false);
        }
    });
    m_task->setCallBackForShow2DDepth([this] () {
        if(!this->ui->Depth->isFullScreen())
        {
            ui->Depth->setParent(nullptr);
            ui->Depth->setWindowFlag(Qt::Window);
            ui->Depth->showFullScreen();
            m_task->setFullScreen(true);
        }
        else
        {
            ui->Depth->setParent(ui->widget_6);
            ui->gridLayout_2->addWidget(ui->Depth, 0, 0);
            ui->Depth->setWindowFlag(Qt::SubWindow);
            ui->Depth->showNormal();
            m_task->setFullScreen(false);
        }
    });
    m_task->setCallBackForShow2DIR([this] () {
        if(!this->ui->IR->isFullScreen())
        {
            ui->IR->setParent(nullptr);
            ui->IR->setWindowFlag(Qt::Window);
            ui->IR->showFullScreen();
            m_task->setFullScreen(true);
        }
        else
        {
            ui->IR->setParent(ui->widget_6);
            ui->gridLayout_2->addWidget(ui->IR, 0, 1);
            ui->IR->setWindowFlag(Qt::SubWindow);
            ui->IR->showNormal();
            m_task->setFullScreen(false);
        }
    });

    ui->IR->hide();
    ui->Depth->hide();
    ui->cloudPoint->hide();

    statuCtl();

}

mainWindow::~mainWindow()
{
    std::fstream out("./Config/lv.json", std::ios_base::out);
    out << slt(Json).str();
    out.close();
    slt(DxyThreadPool).stop();
    slt(LvApi).shutDown();
    delete ui;
    // delete m_task;
}

void mainWindow::changeMinMax()
{
    if(m_isMax == false)
    {
        showFullScreen();
    }
    else
    {
        showNormal();
    }
    m_isMax = !m_isMax;
}

bool mainWindow::event(QEvent *event)
{
    if (event->type() == QEvent::HoverMove) {
        QHoverEvent *hoverEvent = static_cast<QHoverEvent *>(event);
        QMouseEvent mouseEvent(QEvent::MouseMove, hoverEvent->pos(),
                               Qt::NoButton, Qt::NoButton, Qt::NoModifier);
        mouseMoveEvent(&mouseEvent);
    }
    return QWidget::event(event);
}

void mainWindow::mouseDoubleClickEvent(QMouseEvent * event)
{
    // qDebug() << event->pos();
    if(event->pos().y() > 40) return;
    changeMinMax();

}

void mainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_bIsPressed = true;
        m_pressPoint = event->globalPos();
    }
    return QWidget::mousePressEvent(event);
}

void mainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if(this->isFullScreen() || event->pos().y() > 40) return;
    if (m_bIsPressed) {
        if (m_bIsResizing) {
            m_movePoint = event->globalPos() - m_pressPoint;
            m_pressPoint += m_movePoint;
        } else {
            if (!m_bIsDoublePressed && windowState() == Qt::WindowMaximized) {
                // restoreWidget();
                QPointF point(width() * ((double)(event->globalPos().x()) / QApplication::desktop()->width()),
                              height() * ((double)(event->globalPos().y()) / QApplication::desktop()->height()));

                move(event->globalPos() - point.toPoint());

                m_pressPoint = event->globalPos();
            }

            QPoint point = event->globalPos() - m_pressPoint;
            move(pos() + point);

            m_pressPoint = event->globalPos();
        }
    }

    if (windowState() != Qt::WindowMaximized) {
        updateRegion(event);
    }

    QWidget::mouseMoveEvent(event);
}

void mainWindow::updateRegion(QMouseEvent *event)
{


    QRect mainRect = geometry();

    int marginTop = event->globalY() - mainRect.y();
    int marginBottom = mainRect.y() + mainRect.height() - event->globalY();
    int marginLeft = event->globalX() - mainRect.x();
    int marginRight = mainRect.x() + mainRect.width() - event->globalX();

    if (!m_bIsResizing) {
        if ( (marginRight >= MARGIN_MIN_SIZE && marginRight <= MARGIN_MAX_SIZE)
             && ((marginBottom <= MARGIN_MAX_SIZE) && marginBottom >= MARGIN_MIN_SIZE) ) {
            m_direction = BOTTOMRIGHT;
            setCursor(Qt::SizeFDiagCursor);
        } else if ( (marginTop >= MARGIN_MIN_SIZE && marginTop <= MARGIN_MAX_SIZE)
                    && (marginRight >= MARGIN_MIN_SIZE && marginRight <= MARGIN_MAX_SIZE)) {
            m_direction = TOPRIGHT;
            setCursor(Qt::SizeBDiagCursor);
        } else if ( (marginLeft >= MARGIN_MIN_SIZE && marginLeft <= MARGIN_MAX_SIZE)
                    && (marginTop >= MARGIN_MIN_SIZE && marginTop <= MARGIN_MAX_SIZE) ) {
            m_direction = TOPLEFT;
            setCursor(Qt::SizeFDiagCursor);
        } else if ( (marginLeft >= MARGIN_MIN_SIZE && marginLeft <= MARGIN_MAX_SIZE)
                    && (marginBottom >= MARGIN_MIN_SIZE && marginBottom <= MARGIN_MAX_SIZE)) {
            m_direction = BOTTOMLEFT;
            setCursor(Qt::SizeBDiagCursor);
        } else if (marginBottom <= MARGIN_MAX_SIZE && marginBottom >= MARGIN_MIN_SIZE) {
            m_direction = DOWN;
            setCursor(Qt::SizeVerCursor);
        } else if (marginLeft <= MARGIN_MAX_SIZE - 1 && marginLeft >= MARGIN_MIN_SIZE - 1) {
            m_direction = LEFT;
            setCursor(Qt::SizeHorCursor);
        } else if (marginRight <= MARGIN_MAX_SIZE && marginRight >= MARGIN_MIN_SIZE) {
            m_direction = RIGHT;
            setCursor(Qt::SizeHorCursor);
        } else if (marginTop <= MARGIN_MAX_SIZE && marginTop >= MARGIN_MIN_SIZE) {
            m_direction = UP;
            setCursor(Qt::SizeVerCursor);
        } else {
            if (!m_bIsPressed) {
                setCursor(Qt::ArrowCursor);
            }
        }
    }

    if (NONE != m_direction) {
        m_bIsResizing = true;
        resizeRegion(marginTop, marginBottom, marginLeft, marginRight);
    }
}

void mainWindow::resizeRegion(int marginTop, int marginBottom, int marginLeft, int marginRight)
{
    if (m_bIsPressed) {
        switch (m_direction) {
        case BOTTOMRIGHT:
        {
            QRect rect = geometry();
            rect.setBottomRight(rect.bottomRight() + m_movePoint);
            setGeometry(rect);
        }
            break;
        case TOPRIGHT:
        {
            if (marginLeft > minimumWidth() && marginBottom > minimumHeight()) {
                QRect rect = geometry();
                rect.setTopRight(rect.topRight() + m_movePoint);
                setGeometry(rect);
            }
        }
            break;
        case TOPLEFT:
        {
            if (marginRight > minimumWidth() && marginBottom > minimumHeight()) {
                QRect rect = geometry();
                rect.setTopLeft(rect.topLeft() + m_movePoint);
                setGeometry(rect);
            }
        }
            break;
        case BOTTOMLEFT:
        {
            if (marginRight > minimumWidth() && marginTop> minimumHeight()) {
                QRect rect = geometry();
                rect.setBottomLeft(rect.bottomLeft() + m_movePoint);
                setGeometry(rect);
            }
        }
            break;
        case RIGHT:
        {
            QRect rect = geometry();
            rect.setWidth(rect.width() + m_movePoint.x());
            setGeometry(rect);
        }
            break;
        case DOWN:
        {
            QRect rect = geometry();
            rect.setHeight(rect.height() + m_movePoint.y());
            setGeometry(rect);
        }
            break;
        case LEFT:
        {
            if (marginRight > minimumWidth()) {
                QRect rect = geometry();
                rect.setLeft(rect.x() + m_movePoint.x());
                setGeometry(rect);
            }
        }
            break;
        case UP:
        {
            if (marginBottom > minimumHeight()) {
                QRect rect = geometry();
                rect.setTop(rect.y() + m_movePoint.y());
                setGeometry(rect);
            }
        }
            break;
        default:
        {
        }
            break;
        }
    } else {
        m_bIsResizing = false;
        m_direction = NONE;
    }
}

void mainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_bIsPressed = false;
        m_bIsResizing = false;
        m_bIsDoublePressed = false;
    }
    QWidget::mouseReleaseEvent(event);
}

void mainWindow::leaveEvent(QEvent *event)
{
    m_bIsPressed = false;
    m_bIsDoublePressed = false;
    m_bIsResizing = false;

    QWidget::leaveEvent(event);
}

void mainWindow::closeEvent(QCloseEvent * event)
{
    // m_timer->stop();
    // std::this_thread::sleep_for(std::chrono::seconds(1));
    std::fstream out("./Config/lv.json", std::ios_base::out);
    out << slt(Json).str();
    out.close();

}

void mainWindow::scanDevice()
{
    
    ui->treeView->setHeaderHidden(true);
    //设置表头
    // model->setHorizontalHeaderLabels(QStringList()<<"devices");
    
    //设置model 
 
    //设置展开
    ui->treeView->expandAll();

    int ret = slt(LvApi).findDevice();

    if(ret == 0)
    {
        ui->statuslab->setText("未找到设备");
        QMessageBox::information(nullptr, "提示", "未找到设备");
    }

    for(int i = 0; i < ret; i++)
    {
        QStandardItem *item = new QStandardItem(slt(LvApi).m_infoList[i].ip);
        item->setEditable(false);
        m_model->setItem(i, item);
    }
}

void mainWindow::on_treeView_clicked(const QModelIndex &index)
{
    // if(ui->openDev->isEnabled() == true)
    // {
    ui->statuslab->setText(ui->treeView->model()->itemData(index)[0].toString());
    ui->openDev->setEnabled(true);
    m_deviceIdx = index.column();
    // }
}

void mainWindow::on_openClicked()
{
    configInit();
    auto deviceInfo = slt(LvApi).selectDevice(m_deviceIdx);
    ui->openDev->setDisabled(true);
    ui->closeDev->setDisabled(false);
    m_task->start();
    ui->setZone_2->setEnabled(true);
    ui->treeView->setEnabled(false);
    ui->findDevices->setEnabled(false);
    
    ui->infoWidget->show();
    ui->IP->setText(tr(deviceInfo.ip));
    ui->SN->setText(tr("2301AG00004"));
    ui->FW->setText(tr("202303231.1.0"));
    ui->Model->setText(tr("D3"));

    ui->IR->show();
    ui->Depth->show();
    ui->cloudPoint->show();

}

void mainWindow::on_stopClicked()
{
    ui->closeDev->setDisabled(true);
    ui->openDev->setDisabled(true);
    m_task->stop();
    slt(LvApi).closeDevice();
    ui->setZone_2->setEnabled(false);
    for(int i = m_model->rowCount() - 1; i >= 0; i--)
    {
        m_model->removeRow(i);
    }
    ui->treeView->setEnabled(true);
    ui->findDevices->setEnabled(true);

    ui->infoWidget->hide();

}

void mainWindow::renderData(int type)
{
    // slt(Json)["ImgSizeScalar"] = Json(this->ui->Depth->height() * 0.8 / 480.0);
    if(this->ui->Depth->width() < this->ui->Depth->height()) slt(Json)["ImgSizeScalar"] = Json((float)this->ui->Depth->width() * 0.8 / 640); 
    else slt(Json)["ImgSizeScalar"] = Json((float)this->ui->Depth->height() * 0.8 / 480); 
    m_task->__render(type);
}

void mainWindow::statuCtl()
{

    /*=======================ExposureTime============================*/
    connect(ui->exposureTimeSlider, &QSlider::sliderReleased, [this] () {
        this->ui->exposureTime->setText(QString().setNum(ui->exposureTimeSlider->value()));
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["ExposureTime"]["ExposureTime"] = Json(ui->exposureTimeSlider->value());
            slt(LvApi).setExposureTime(VzExposureControlMode_Manual, ui->exposureTimeSlider->value());

        });
    });
    connect(ui->exposureTime, &QLineEdit::editingFinished, [this] () {
        ui->exposureTimeSlider->setValue(ui->exposureTime->text().toInt());
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["ExposureTime"]["ExposureTime"] = Json(ui->exposureTime->text().toInt());
            slt(LvApi).setExposureTime(this->ui->Auto->isChecked() ? VzExposureControlMode_Auto : VzExposureControlMode_Manual, ui->exposureTimeSlider->value());
        });
    });

  
    connect(ui->Auto, &QRadioButton::clicked, [this] (bool checked) {
        if(ui->HDRMode->isChecked())
        {
            ui->Auto->setChecked(false);
            ui->Manual->setChecked(true);
            QMessageBox::information(nullptr, "提示", "请先关闭HDR在开启自动积分");
            return;
        }
        this->ui->exposureTimeSlider->setEnabled(false);
        this->ui->exposureTime->setEnabled(false);
        this->ui->exposureTimeLab->setEnabled(false);
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["ExposureTime"]["Auto"] = Json(checked);
            slt(LvApi).setExposureTimeMode(VzExposureControlMode_Auto);
            slt(LvApi).setExposureTime(this->ui->Auto->isChecked() ? VzExposureControlMode_Auto : VzExposureControlMode_Manual, (int)slt(Json)["ExposureTime"]["ExposureTime"].asInt());
        });
        auto para = slt(LvApi).getExposureTime();
    });

    connect(ui->Manual, &QRadioButton::clicked, [this] (bool checked) {
        this->ui->exposureTimeSlider->setEnabled(true);
        this->ui->exposureTime->setEnabled(true);
        this->ui->exposureTimeLab->setEnabled(true);
        this->ui->HDRMode->setEnabled(true);
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["ExposureTime"]["Manual"] = Json(checked);
            slt(LvApi).setExposureTimeMode(VzExposureControlMode_Manual);
            slt(LvApi).setExposureTime(this->ui->Manual->isChecked() ? VzExposureControlMode_Auto : VzExposureControlMode_Manual, (int)slt(Json)["ExposureTime"]["ExposureTime"].asInt());
        });
    });
    
    connect(ui->HDRMode, &QCheckBox::clicked, [this] (bool checked) {
        // ui->Auto->setEnabled(!checked);
        ui->Manual->setChecked(true);
        this->ui->exposureTimeSlider->setEnabled(true);
        this->ui->exposureTime->setEnabled(true);
        this->ui->exposureTimeLab->setEnabled(true);
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["ExposureTime"]["Manual"] = Json(checked);
            slt(LvApi).setExposureTimeMode(VzExposureControlMode_Manual);
            slt(LvApi).setHDRMode(checked);
        });
    });

    /*=============================Control================================*/
    connect(ui->modeComBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [this] (int index) {
        // slt(DxyThreadPool).addTask([=] () {
            if(index == 0) 
            {
                this->ui->closeDev->setEnabled(true);
                this->ui->tigger->hide();
                this->m_task->setlock(false);
            }
            else if(index == 1)
            {
                this->ui->closeDev->setEnabled(false);
                this->ui->tigger->hide();
                this->m_task->setlock(false);
                while(!this->m_task->setlock(true)) {}
            }
            else if(index == 2)
            {
                this->ui->closeDev->setEnabled(false);
                this->ui->tigger->show();
                this->m_task->setlock(false);
                while(!this->m_task->setlock(true)) {}
            }  
        // });
    });

    connect(ui->tigger, &QPushButton::clicked, [this] (bool checked) {
        this->m_task->workForTigger();
    });

    connect(ui->colorMapMaxSlider, &QSlider::sliderReleased, [this] () {
        if(ui->colorMapMaxSlider->value() < ui->colorMapMinSlider->value())
        {
            QMessageBox::information(nullptr, "操作错误", "最大色彩映射距离不能小于最小色彩映射距离");
            ui->colorMapMaxSlider->setValue(slt(Json)["Control"]["ColorMapMax"].asInt());
            return;
        }
        ui->colorMaxEdit->setText(QString().setNum(ui->colorMapMaxSlider->value()));
        slt(Json)["Control"]["ColorMapMax"] = Json(ui->colorMapMaxSlider->value());
    });
    connect(ui->colorMaxEdit, &QLineEdit::editingFinished, [this] () {
        if(ui->colorMaxEdit->text().toInt() < ui->colorMinEidt->text().toInt())
        {
            QMessageBox::information(nullptr, "操作错误", "最大色彩映射距离不能小于最小色彩映射距离");
            ui->colorMaxEdit->setText(QString().setNum(slt(Json)["Control"]["ColorMapMax"].asInt()));
            return;
        }
        ui->colorMapMaxSlider->setValue(ui->colorMaxEdit->text().toInt());
        slt(Json)["Control"]["ColorMapMax"] = Json(ui->colorMapMaxSlider->value());
    });
    
    connect(ui->colorMapMinSlider, &QSlider::sliderReleased, [this] () {
        if(ui->colorMapMaxSlider->value() < ui->colorMapMinSlider->value())
        {
            QMessageBox::information(nullptr, "操作错误", "最小色彩映射距离不能大于最大色彩映射距离");
            ui->colorMapMinSlider->setValue(slt(Json)["Control"]["ColorMapMin"].asInt());
            return;
        }
        ui->colorMinEidt->setText(QString().setNum(ui->colorMapMinSlider->value()));
        slt(Json)["Control"]["ColorMapMin"] = Json(ui->colorMapMinSlider->value());
    });
    connect(ui->colorMinEidt, &QLineEdit::editingFinished, [this] () {
        if(ui->colorMaxEdit->text().toInt() < ui->colorMinEidt->text().toInt())
        {
            QMessageBox::information(nullptr, "操作错误", "最小色彩映射距离不能大于最大色彩映射距离");
            ui->colorMinEidt->setText(QString().setNum(slt(Json)["Control"]["ColorMapMin"].asInt()));
            return;
        }
        ui->colorMapMinSlider->setValue(ui->colorMinEidt->text().toInt());
        slt(Json)["Control"]["ColorMapMin"] = Json(ui->colorMapMinSlider->value());
    });


    connect(ui->GammGainSlider, &QSlider::sliderReleased, [this] () {
        ui->IRGammGainEidt->setText(QString().setNum(ui->GammGainSlider->value()));
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Control"]["IRGammGain"] = Json(ui->GammGainSlider->value());
            slt(LvApi).setIRGMMGain(ui->GammGainSlider->value());
        });
    });
    connect(ui->IRGammGainEidt, &QLineEdit::editingFinished, [this] () {
        ui->GammGainSlider->setValue(ui->IRGammGainEidt->text().toInt());
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Control"]["IRGammGain"] = Json(ui->GammGainSlider->value());
            slt(LvApi).setIRGMMGain(ui->GammGainSlider->value());
        });
    });

    connect(ui->FrameRateSlider, &QSlider::sliderReleased, [this] () {
        ui->FrameRateEidt->setText(QString().setNum(ui->FrameRateSlider->value()));
        ui->exposureTimeSlider->setMaximum(getMaxExposureFromFrameRate(ui->FrameRateSlider->value()));
        slt(Json)["Control"]["MaxExposureTime"] = Json(getMaxExposureFromFrameRate(ui->FrameRateSlider->value()));
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Control"]["FrameRate"] = Json(ui->FrameRateSlider->value());
            slt(Json)["Control"]["IsSetFrameRate"] = Json(true);
        });
    });
    connect(ui->FrameRateEidt, &QLineEdit::editingFinished, [this] () {
        ui->FrameRateSlider->setValue(ui->FrameRateEidt->text().toInt());
        ui->exposureTimeSlider->setMaximum(getMaxExposureFromFrameRate(ui->FrameRateSlider->value()));
        slt(Json)["Control"]["MaxExposureTime"] = Json(getMaxExposureFromFrameRate(ui->FrameRateSlider->value()));
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Control"]["FrameRate"] = Json(ui->FrameRateSlider->value());
            slt(Json)["Control"]["IsSetFrameRate"] = Json(true);
        });
    });
    /*=============================Filter================================*/

    connect(ui->Spatial_Filter, &QCheckBox::clicked, [this] (bool checked) {
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["SpatialFilter"] = Json(checked);
            slt(LvApi).setSpatialFilter(checked);
        });
    });

    connect(ui->Black_BG, &QCheckBox::clicked, [this] (bool checked) {
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["BlackBG"] = Json(checked);
            m_task->setBlackBG(checked);
        });
    });

    connect(ui->FillHole, &QCheckBox::clicked, [this] (bool checked) {
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["FillHole"] = Json(checked);
            slt(LvApi).setFillHoleEnable(checked);
        });
    });

    connect(ui->TimeFilterCkBox, &QCheckBox::clicked, [this] (bool checked) {
        this->ui->TimeFilterEdit->setEnabled(checked);
        this->ui->TimeFilterLab->setEnabled(checked);
        this->ui->TimeFilterSlid->setEnabled(checked);
        static int TimeFilterthreshold;
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["TimeFilterFlag"] = Json(checked);
            slt(LvApi).setTimeFilter(checked, TimeFilterthreshold);
        });
    });

    connect(ui->TimeFilterSlid, &QSlider::sliderReleased, [this] () {
        ui->TimeFilterEdit->setText(QString().setNum(ui->TimeFilterSlid->value()));
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["TimeFilter"] = Json(ui->TimeFilterSlid->value());
            slt(LvApi).setTimeFilter(true, ui->TimeFilterSlid->value());
        });
    });
    connect(ui->TimeFilterEdit, &QLineEdit::editingFinished, [this] () {
        ui->TimeFilterSlid->setValue(ui->TimeFilterEdit->text().toInt());
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["TimeFilter"] = Json(ui->TimeFilterSlid->value());
            slt(LvApi).setTimeFilter(true, ui->TimeFilterSlid->value());
        });
    });

    connect(ui->FlyFilterCkBox, &QCheckBox::clicked, [this] (bool checked) {
        this->ui->FlyFilterEidt->setEnabled(checked);
        this->ui->FlyFilterLab->setEnabled(checked);
        this->ui->FlyFilterSlid->setEnabled(checked);
        // static int FlyFilterthreshold;
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["FlyingPixFilterFlag"] = Json(checked);
            slt(LvApi).setFlyingPixelFilter(checked, slt(Json)["Filter"]["TimeFilter"].asInt());
        });
    });

    connect(ui->FlyFilterSlid, &QSlider::sliderReleased, [this] () {
        ui->FlyFilterEidt->setText(QString().setNum(ui->FlyFilterSlid->value()));
        // static int FlyFilterthreshold;
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["FlyingPixFilter"] = Json(ui->FlyFilterSlid->value());
            // FlyFilterthreshold = ui->FlyFilterSlid->value();
            slt(LvApi).setFlyingPixelFilter(true, ui->FlyFilterSlid->value());
        });
    });
    connect(ui->FlyFilterEidt, &QLineEdit::editingFinished, [this] () {
        ui->FlyFilterSlid->setValue(ui->FlyFilterEidt->text().toInt());
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["FlyingPixFilter"] = Json(ui->FlyFilterSlid->value());
            // FlyFilterthreshold = ui->FlyFilterSlid->value();
            slt(LvApi).setFlyingPixelFilter(true, ui->FlyFilterSlid->value());
        });
    });


    connect(ui->ConfFilterCkBox, &QCheckBox::clicked, [this] (bool checked) {
        this->ui->ConfFilterEdit->setEnabled(checked);
        this->ui->ConfFilterLab->setEnabled(checked);
        this->ui->ConfFilterSlid->setEnabled(checked);
        // static int ConfFilterthreshold;
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["ConfidenceFilterFlag"] = Json(checked);
            slt(LvApi).setConfidenceFilter(checked, slt(Json)["Filter"]["FlyingPixFilter"].asInt());
        });
    });

    connect(ui->ConfFilterSlid, &QSlider::sliderReleased, [this] () {
        ui->ConfFilterEdit->setText(QString().setNum(ui->ConfFilterSlid->value()));
        // static int ConfFilterthreshold;
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["ConfidenceFilter"] = Json(ui->ConfFilterSlid->value());
            // ConfFilterthreshold = ui->ConfFilterSlid->value();
            slt(LvApi).setConfidenceFilter(true, ui->ConfFilterSlid->value());
        });
    });
    connect(ui->ConfFilterEdit, &QLineEdit::editingFinished, [this] () {
        ui->ConfFilterSlid->setValue(ui->ConfFilterEdit->text().toInt());
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["ConfidenceFilter"] = Json(ui->ConfFilterSlid->value());
            // ConfFilterthreshold = ui->ConfFilterSlid->value();
            slt(LvApi).setConfidenceFilter(true, ui->ConfFilterSlid->value());
        });
    });

    connect(ui->filterResetsBtn, &QPushButton::clicked, [=] () {
        ui->Spatial_Filter->setChecked(true);
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["BlackBG"] = Json(true);
            m_task->setBlackBG(true);
        });

        ui->FillHole->setChecked(true);
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["FillHole"] = Json(true);
            slt(LvApi).setFillHoleEnable(true);
        });

        ui->TimeFilterEdit->setText(QString().setNum(1));
        ui->TimeFilterSlid->setValue(1);
        ui->TimeFilterCkBox->setChecked(true);
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["TimeFilter"] = Json(1);
            slt(LvApi).setTimeFilter(true, 1);
        });
    
        ui->ConfFilterEdit->setText(QString().setNum(13));
        ui->ConfFilterSlid->setValue(13);
        ui->ConfFilterCkBox->setChecked(true);
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["ConfidenceFilter"] = Json(13);
            slt(LvApi).setConfidenceFilter(true, 13);
        });

        ui->FlyFilterSlid->setValue(8);
        ui->FlyFilterCkBox->setChecked(true);
        ui->FlyFilterEidt->setText(QString().setNum(8));
        slt(DxyThreadPool).addTask([=] () {
            slt(Json)["Filter"]["FlyingPixFilter"] = Json(8);
            slt(LvApi).setFlyingPixelFilter(true, 8);
        });

    });

    /*=============================Image================================*/
    connect(ui->IRCkBox, &QCheckBox::clicked, [this] (bool checked) {
        slt(Json)["Image"]["IR"] = Json(checked);
    });

    connect(ui->DepthCkBox, &QCheckBox::clicked, [this] (bool checked) {
        ui->CloudPointCkBox->setChecked(checked ? ui->CloudPointCkBox->isChecked() : false);
        ui->Black_BG->setEnabled(checked);
        this->ui->CloudPointCkBox->setChecked(false);
        this->m_task->showWindow(ui->cloudPoint, checked ? ui->CloudPointCkBox->isChecked() : false);
        slt(Json)["Image"]["CloudPoint"] = Json(false);
        slt(Json)["Image"]["CloudPoint"] = Json(checked ? ui->CloudPointCkBox->isChecked() : false);
        slt(Json)["Image"]["Depth"] = Json(checked);
    });

    connect(ui->CloudPointCkBox, &QCheckBox::clicked, [this] (bool checked) {
        this->ui->DepthCkBox->setChecked(true);
        slt(Json)["Image"]["Depth"] = Json(true);
        slt(Json)["Image"]["CloudPoint"] = Json(checked);
    });

    

    connect(ui->saveBtn, &QPushButton::clicked, [this] () {
        QString path = QFileDialog::getExistingDirectory(nullptr, "保存");
        slt(Json)["SavePath"] = Json(std::string(path.toLocal8Bit()));
        this->m_task->saveData();
    });
}

void mainWindow::configInit()
{
    // qDebug() << slt(Json).str().c_str();
    ui->setZone_2->setEnabled(true);

    ui->GammGainSlider->setValue(slt(Json)["Control"]["IRGammGain"].asInt());
    ui->IRGammGainEidt->setText(QString().setNum(slt(Json)["Control"]["IRGammGain"].asInt()));
    ui->FrameRateSlider->setValue(slt(Json)["Control"]["FrameRate"].asInt());
    ui->FrameRateEidt->setText(QString().setNum(slt(Json)["Control"]["FrameRate"].asInt()));
    // ui->Auto->setChecked(slt(Json)["ExposureTime"]["Auto"].asBool());
    ui->Auto->setChecked(false);
    ui->Auto->setEnabled(false);
    ui->Manual->setChecked(true);
    ui->exposureTimeSlider->setValue(slt(Json)["ExposureTime"]["ExposureTime"].asInt());
    ui->exposureTime->setText(QString().setNum(slt(Json)["ExposureTime"]["ExposureTime"].asInt()));
    ui->HDRMode->setChecked(slt(Json)["ExposureTime"]["HDREnabled"].asBool());
    slt(Json)["Image"]["IR"]= Json(true);
    slt(Json)["Image"]["Depth"] = Json(true);
    slt(Json)["Image"]["CloudPoint"] = Json(true);
    ui->Black_BG->setChecked(slt(Json)["Filter"]["BlackBG"].asBool());
    ui->FillHole->setChecked(slt(Json)["Filter"]["FillHole"].asBool());
    ui->Spatial_Filter->setChecked(slt(Json)["Filter"]["SpatialFilter"].asBool());
    ui->TimeFilterSlid->setValue(slt(Json)["Filter"]["TimeFilter"].asInt());
    ui->TimeFilterEdit->setText(QString().setNum(slt(Json)["Filter"]["TimeFilter"].asInt()));
    ui->FlyFilterSlid->setValue(slt(Json)["Filter"]["FlyingPixFilter"].asInt());
    ui->FlyFilterEidt->setText(QString().setNum(slt(Json)["Filter"]["FlyingPixFilter"].asInt()));
    ui->ConfFilterSlid->setValue(slt(Json)["Filter"]["ConfidenceFilter"].asInt());
    ui->ConfFilterEdit->setText(QString().setNum(slt(Json)["Filter"]["ConfidenceFilter"].asInt()));
    m_task->setBlackBG(ui->Black_BG->isChecked());
    ui->DepthCkBox->setChecked(true);
    ui->IRCkBox->setChecked(true);
    ui->CloudPointCkBox->setChecked(true);
    ui->exposureTimeLab->setEnabled(!ui->Auto->isChecked());
    ui->exposureTimeSlider->setEnabled(!ui->Auto->isChecked());
    ui->exposureTime->setEnabled(!ui->Auto->isChecked());
    ui->Black_BG->setEnabled(true);
    ui->colorMapMaxSlider->setValue(slt(Json)["Control"]["ColorMapMax"].asInt());
    ui->colorMaxEdit->setText(QString().setNum(slt(Json)["Control"]["ColorMapMax"].asInt()));
    ui->colorMapMinSlider->setValue(slt(Json)["Control"]["ColorMapMin"].asInt());
    ui->colorMinEidt->setText(QString().setNum(slt(Json)["Control"]["ColorMapMin"].asInt()));
    ui->tigger->hide();
    ui->infoWidget->hide();
    ui->exposureTimeSlider->setMaximum(slt(Json)["Control"]["MaxExposureTime"].asInt());
    ui->Auto->setEnabled(true);
    ui->setZone_2->setEnabled(false);
}


 